<template>
    <el-form style="margin: 10px 0;" label-width="100px">
        <el-form-item label="SPU名称">
            <el-input placeholder="请输入SPU名称" v-model="SpuParams.spuName"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌">
            <el-select placeholder="请输入SPU品牌" style="width: 240px" v-model="SpuParams.tmId">
                <el-option v-for="(item) in AllTradeMark" :key="item.id" :label="item.tmName"
                    :value="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="请输入SPU描述" v-model="SpuParams.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图标">
            <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload" list-type="picture-card"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handlerUpload">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" style="width:100%;height: 100%;" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU属性">
            <el-select v-model="saleAttrIdAndValueName"
                :placeholder="unSelectSaleAttr.length ? `还未选择${unSelectSaleAttr.length}个销售属性` : '暂无属性'"
                style="width: 240px">
                <el-option :value="`${item.id}:${item.name}`" v-for="(item) in unSelectSaleAttr" :key="item.id"
                    :label="item.name"></el-option>

            </el-select>
            <el-button style="margin-left: 10px ;" icon="Plus" type="primary" @click="addSaleAttr"
                :disabled="saleAttrIdAndValueName ? false : true">添加属性</el-button>
            <el-table border style="margin: 10px 0;" :data="saleAttr">
                <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                <el-table-column label="销售属性名字" width="120px" prop="saleAttrName"></el-table-column>
                <el-table-column label="销售属性值">
                    <template #="{ row }">
                        <el-tag style="margin:0px 5px" @close="row.spuSaleAttrValueList.splice(index, 1)"
                            v-for="(item, index) in row.spuSaleAttrValueList" :key="row.id" class="mx-1" closable>
                            {{ item.saleAttrValueName }}
                        </el-tag>
                        <el-input style="width:100px" size="small" v-model="row.saleAttrValue" v-if="row.flag == true"
                            @blur="toLook(row)"></el-input>
                        <el-button v-else size="small" icon="Plus" type="success" @click="toEdit(row)"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120px">
                    <template #="{ $index }">
                        <el-button type="primary" size="small" icon="Delete"
                            @click="saleAttr.splice($index, 1)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button :disabled="saleAttr.length ? false : true" type="primary" size="default"
                @click="save">保存</el-button>
            <el-button type="primary" size="default" @click="cancle">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { reqAllTradeMark, reqSpuImageList, reqSpuHasSaleAttr, reqAllSaleAttr, reqAddOrUpdateSpu } from '@/api/product/spu'
import type { SaleAttrValue, SpuData, HasSaleAttr, SaleAttr, SpuImg, Trademark, AllTradeMark, SpuHasImg, SaleAttrResponseData, HasSaleAttrResponseData } from '@/api/product/spu/type';
import { ElMessage } from 'element-plus';
let $emit = defineEmits(['changeScene'])
const cancle = () => {
    $emit('changeScene', {flag:0,params:'update'})
}
//存储已有的SPU这些数据
let AllTradeMark = ref<Trademark[]>([]);
//商品图片
let imgList = ref<SpuImg[]>([]);
//已有的SPU销售属性
let saleAttr = ref<SaleAttr[]>([]);
//全部销售属性
let allSaleAttr = ref<HasSaleAttr[]>([]);
//存储已有的SPU对象
let SpuParams = ref<SpuData>({
    category3Id: "",//收集三级分类的ID
    spuName: "",//SPU的名字
    description: "",//SPU的描述
    tmId: '',//品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
});
// 定义控制对话框显隐的
let dialogVisible = ref<boolean>(false)
// 定义图片上传路径
let dialogImageUrl = ref<string>('')
//将来收集还未选择的销售属性的ID与属性值的名字
let saleAttrIdAndValueName = ref<string>('')
// 定义获取已有spu数据的四个方法
const initHasSpuData = async (spu: SpuData) => {
    // 存储已有的spu对象
    SpuParams.value = spu;
    // 获取所有品牌的数据
    let result: AllTradeMark = await reqAllTradeMark()
    // 获取所有品牌图片的方法
    let result1: SpuHasImg = await reqSpuImageList((spu.id as number))
    //获取已有的SPU销售属性的数据
    let result2: SaleAttrResponseData = await reqSpuHasSaleAttr((spu.id as number));
    //获取整个项目全部SPU的销售属性
    let result3: HasSaleAttrResponseData = await reqAllSaleAttr();
    //存储全部品牌的数据
    AllTradeMark.value = result.data;
    //SPU对应商品图片
    imgList.value = result1.data.map((item) => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    })
    //存储已有的SPU的销售属性
    saleAttr.value = result2.data;
    //存储全部的销售属性
    allSaleAttr.value = result3.data;
}
// 点击预览图片按钮的回调
const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
}
// 点击删除图片按钮的回调
const handleRemove = (file: any) => {
    console.log(file);
}

//照片钱上传成功之前的钩子约束文件的大小与类型
const handlerUpload = (file: any) => {
    if (file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') {
        if (file.size / 1024 / 1024 < 3) {
            return true;
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件务必小于3M'
            })
            return false;
        }
    } else {
        ElMessage({
            type: 'error',
            message: '上传文件务必PNG|JPG|GIF'
        })
        return false;
    }
}

// 计算当前SPU还未添加的销售属性
const unSelectSaleAttr = computed(() => {
    //全部销售属性:颜色、版本、尺码
    //已有的销售属性:颜色、版本
    let unSelectSaleAttr = allSaleAttr.value.filter((item) => {
        return saleAttr.value.every((item1) => {
            return item.name != item1.saleAttrName
        })
    })
    return unSelectSaleAttr
})

// 点击添加属性按钮的回调
const addSaleAttr = () => {

    // 拿到收集到的数据
    /*
    "baseSaleAttrId": number,
    "saleAttrName": string,
    "spuSaleAttrValueList": SpuSaleAttrValueList
    */
    const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
    // 创建一个销售属性对象，传递给服务器
    let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
    }
    //追加到数组当中
    saleAttr.value.push(newSaleAttr);
    //清空收集的数据
    saleAttrIdAndValueName.value = '';
}

// 点击销售属性值按钮的回调
const toEdit = (row: SaleAttr) => {
    // 切换未编辑模式
    row.flag = true
    //添加新的属性值
    row.saleAttrValue = ''
}

// 属性值文本框失去焦点时候的回调
const toLook = (row: SaleAttr) => {
    // 收集到的数据 属性值id和具体的属性值
    const { baseSaleAttrId, saleAttrValue } = row;
    //整理成服务器需要的属性值形式
    let newSaleAttrValue: SaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: (saleAttrValue as string)
    }
    //非法情况判断
    // saleAttrValue 这是文本框输入的值，判断其是否为空，是否重复
    if ((saleAttrValue as string).trim() == '') {
        ElMessage({
            type: 'error',
            message: '属性值不能为空的'
        })
        //切换为查看模式
        row.flag = false;
        return;
    }
    //判断属性值是否在数组当中存在
    let repeat = row.spuSaleAttrValueList.find(item => {
        return item.saleAttrValueName == saleAttrValue;
    })

    if (repeat) {
        ElMessage({
            type: 'error',
            message: '属性值重复,请重新输入'
        })
        //切换为查看模式
        row.flag = false;
        return;
    }



    //追加新的属性值对象
    row.spuSaleAttrValueList.push(newSaleAttrValue);
    //切换为查看模式
    row.flag = false;
}

// 点击保存按钮添加的回调
const save = async () => {
    // 整理收集到的数据，添加到SpuParams中
    //1.整理照片墙的数据
    SpuParams.value.spuImageList = imgList.value.map((item: any) => {
        return {
            // 服务器需要的字段是imgName和imgUrl，所以需要对字段进行转换
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url
        }
    })
    // 2.整理销售属性数据
    SpuParams.value.spuSaleAttrList = saleAttr.value
    // 数据整理完毕，发送请求，将数据带给服务器
    let result: any = await reqAddOrUpdateSpu(SpuParams.value);
    if (result.code === 200) {
        ElMessage({
            type: 'success',
            message: SpuParams.value.id ? '更新成功' : '添加成功'
        })
        //通知父组件切换场景为0
        $emit('changeScene', { flag: 0, params: SpuParams.value.id ? 'update' : 'add' });
    } else {
        ElMessage({
            type: 'error',
            message: SpuParams.value.id ? '更新失败' : '添加失败'
        })
    }
}

// 初始化添加spu的方法
const initAddSpu = async (c3Id: number | string) => {
    //清空数据
    Object.assign(SpuParams.value, {
        category3Id: "",//收集三级分类的ID
        spuName: "",//SPU的名字
        description: "",//SPU的描述
        tmId: '',//品牌的ID
        spuImageList: [],
        spuSaleAttrList: [],
    });
    //清空照片
    imgList.value = [];
    //清空销售属性
    saleAttr.value = [];
    saleAttrIdAndValueName.value = '';
    // 存储三级分类的id
    SpuParams.value.category3Id = c3Id;
    // 获取全部品牌的数据
    let result: AllTradeMark = await reqAllTradeMark()
    //获取整个项目全部SPU的销售属性
    let result1: HasSaleAttrResponseData = await reqAllSaleAttr();
    // 整理数据
    //存储数据
    AllTradeMark.value = result.data;
    allSaleAttr.value = result1.data;
}

// 对外暴露这个方法
defineExpose({
    initHasSpuData,
    initAddSpu
})
</script>
<style lang="scss" scoped></style>